﻿using Castle.DynamicProxy;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Framework.LinkTrackingLog.AI_Deepseek
{
    /// <summary>
    /// 方法执行拦截器
    /// 职责：拦截业务方法调用并记录执行时间
    /// </summary>
    public class MethodExecutionInterceptor : IInterceptor
    {
        private readonly IMethodMonitoringService _monitoringService;

        public MethodExecutionInterceptor(IMethodMonitoringService monitoringService)
        {
            _monitoringService = monitoringService;
        }

        /// <summary>
        /// 拦截方法调用
        /// </summary>
        public void Intercept(IInvocation invocation)
        {
            // 获取方法元数据
            var methodInfo = invocation.Method;

            // 检查方法或类是否标记了[NoMonitor]特性
            if (methodInfo.GetCustomAttributes(typeof(NoMonitorAttribute), true).Any() ||
                methodInfo.DeclaringType.GetCustomAttributes(typeof(NoMonitorAttribute), true).Any())
            {
                // 如果标记了排除特性，直接执行原方法
                invocation.Proceed();
                return;
            }

            // 构建方法全名：ClassName.MethodName
            var methodName = $"{invocation.TargetType.Name}.{methodInfo.Name}";

            // 开始监控
            using (_monitoringService.BeginMonitor(methodName))
            {
                // 执行实际方法
                invocation.Proceed();
            }
            // using块结束时自动记录执行时间
        }
    }
}
